# Create your views here.
from django.http import HttpResponse
from django.http import Http404
from django.template import RequestContext
from django.shortcuts import get_object_or_404
from django.shortcuts import get_list_or_404
from django.shortcuts import render_to_response
from django.contrib.auth.models import User
from django.views.decorators.csrf import csrf_protect
#from forms import RegistrationForm
from forms import *
import ps3t.myps3t.models as db
import subprocess

# Toda pagina processada ele vai tentar
# acessar o banco para ver se o usuario eh valido
# se for ele retorna o "pic_url" dele
def contextUser(request):
	online_users = get_online_users(10)
	try:
		user = db.userInfo.objects.get(auth=request.user)
	except :
		return {'user' : '', 'online_users': online_users} # an empty string

	return {'user' : user, 'online_users' : online_users }

def user_compare(user_1, user_2):

	user_a = user_1[0]
	user_b = user_2[0]

	if int(user_a.points) != int(user_b.points):
		return int(user_a.points - user_b.points)

	return (user_compare_rarity(user_a, user_b))

def user_compare_rarity(user_a, user_b):

	if int(user_a.platinum) != int(user_b.platinum):
		return int(user_a.platinum - user_b.platinum)

	if int(user_a.gold) != int(user_b.gold):
		return int(user_a.gold - user_b.gold)

	if int(user_a.silver) != int(user_b.silver):
		return int(user_a.silver - user_b.silver)

	if int(user_a.bronze) != int(user_b.bronze):
		return int(user_a.bronze - user_b.bronze)

	return 0

def game_rank_compare(game_a, game_b):
	if int(game_a[6]) != int(game_b[6]):
		return int(game_a[6] - game_b[6])

	return int(game_a[3]) != int(game_b[3])

def game_compare(game_a, game_b):
	return int(game_a.last.total - game_b.last.total)

def rank_rarity(request):

	users = db.userTrophy.objects.exclude(rank = 0)
	user_list = []

	for user in users:

		try:
			dif = setUserDif(user)
		except:
			pass

		user_list.append(user)

	user_list.sort(user_compare_rarity, reverse=True)

	i=1
	user_list_rank = []
	for user in user_list:
		user_list_rank.append([i, user])
		i += 1

	paginator = Paginator(user_list_rank, 50) # Show 30 per page

	# Make sure page request is an int. If not, deliver first page.
	try:
		page = int(request.GET.get('page', '1'))
	except ValueError:
		page = 1

	try:
		user_list_rank = paginator.page(page)
	except (EmptyPage, InvalidPage):
		user_list_rank = paginator.page(paginator.num_pages)

	return render_to_response('RankRarity.html',
				{'users' : user_list_rank },
				context_instance=RequestContext(request))

# Rank principal, ordenado por pontos
def rankWeek(request):
	users     = db.userTrophy.objects.exclude(rank = 0).order_by('rank')

	user_list = []

	for user in users:
		try:
			dif = setUserWeekDif(user)
		except:
			pass

		user_list.append([user, dif])

	user_list.sort(user_compare, reverse=True)

	i=1
	user_list_rank = []
	for user, dif in user_list:
		user_list_rank.append([i, user, dif])
		i += 1

	paginator = Paginator(user_list_rank, 50) # Show 30 per page

	# Make sure page request is an int. If not, deliver first page.
	try:
		page = int(request.GET.get('page', '1'))
	except ValueError:
		page = 1

	try:
		user_list_rank = paginator.page(page)
	except (EmptyPage, InvalidPage):
		user_list_rank = paginator.page(paginator.num_pages)

	return render_to_response('RankWeek.html',
				{'users' : user_list_rank },
				context_instance=RequestContext(request))

def rank(request):

	users     = db.userTrophy.objects.exclude(rank = 0).order_by('rank')
	new_users = db.userTrophy.objects.filter(rank = 0).order_by('-date_update')

	user_list = []

	for user in users:

		try:
			dif = setUserDif(user)
		except:
			pass

		user_list.append([user, dif])

	#user_list.sort(user_compare, reverse=True)
	paginator = Paginator(user_list, 50) # Show 30 per page

	# Make sure page request is an int. If not, deliver first page.
	try:
		page = int(request.GET.get('page', '1'))
	except ValueError:
		page = 1

	try:
		user_list = paginator.page(page)
	except (EmptyPage, InvalidPage):
		user_list = paginator.page(paginator.num_pages)

	return render_to_response('Rank.html',
				{'users' : user_list,
				'new_users': new_users},
				context_instance=RequestContext(request))

def setUserWeekDif(user):
	user.platinum   = user.platinum   - user.last_trophy.platinum
	user.gold       = user.gold       - user.last_trophy.gold
	user.silver     = user.silver     - user.last_trophy.silver
	user.bronze     = user.bronze     - user.last_trophy.bronze
	user.total      = user.total      - user.last_trophy.total
	user.points     = user.points     - user.last_trophy.points
	user.level      = user.level      - user.last_trophy.level

	if user.level != 0:
		user.perc_level = (user.perc_level+100) - user.last_trophy.perc_level
	else:
		user.perc_level = user.perc_level - user.last_trophy.perc_level

	return 0

def setUserDif(user):

	#if user.last_trophy.rank == 0:
	#	user.last_trophy.platinum   = 0
	#	user.last_trophy.gold       = 0
	#	user.last_trophy.silver     = 0
	#	user.last_trophy.bronze     = 0
	#	user.last_trophy.total      = 0
	#	user.last_trophy.points     = 0
	#	user.last_trophy.level      = 0
	#	user.last_trophy.perc_level = 0
	#	user.last_trophy.rank       = 0
	#	return 1

	user.last_trophy.platinum   = user.platinum   - user.last_trophy.platinum
	user.last_trophy.gold       = user.gold       - user.last_trophy.gold
	user.last_trophy.silver     = user.silver     - user.last_trophy.silver
	user.last_trophy.bronze     = user.bronze     - user.last_trophy.bronze
	user.last_trophy.total      = user.total      - user.last_trophy.total
	user.last_trophy.points     = user.points     - user.last_trophy.points
	user.last_trophy.level      = user.level      - user.last_trophy.level
	user.last_trophy.perc_level = user.perc_level - user.last_trophy.perc_level

	user.last_trophy.rank = user.last_trophy.rank - user.rank

	if user.last_trophy.rank < 0:
		return 0
	else:
		return 1


def setGameDif(game):

	game.last.platinum   = game.platinum - game.last.platinum
	game.last.gold       = game.gold     - game.last.gold
	game.last.silver     = game.silver   - game.last.silver
	game.last.bronze     = game.bronze   - game.last.bronze
	game.last.total      = game.total    - game.last.total

def logoutUser(request):
	logout(request)
	return rank(request)

		
def createUser(form):

	username  = form.cleaned_data['username']
	first_name= form.cleaned_data['first_name']
	last_name = form.cleaned_data['last_name']
	email     = form.cleaned_data['email']
	birth     = form.cleaned_data['birth']
	password  = form.cleaned_data['password2']

	# Cria o usuario do sistema
	user_db = User.objects.create_user(username, email, password)
	user_db.first_name = first_name
	user_db.last_name  = last_name
	user_db.save()

	# Cria as informacoes adicionais dele
	user_info_db = db.userInfo( auth = user_db,
		birth = birth)
	user_info_db.save()

	# Adiciona na fila para atualizacoes
	queue = db.updateQueue(	user = user_db, type = '1')
	queue.save()

	return user_info_db;


def register(request):
	if request.method=='POST':
		form = RegistrationForm(request.POST)
		if form.is_valid():
			user = createUser(form)
			return render_to_response('Register.html', {'user': user},
				context_instance=RequestContext(request))
	else:
		form = RegistrationForm()

	return render_to_response('Register.html', {'form': form},
								context_instance=RequestContext(request))

# Trofeus referente a um jogo do user
def userGameTrophy(request, userName, game):
	try:
		user_auth = User.objects.get(username=userName)
		user = db.userInfo.objects.get(auth=user_auth)
	except db.userInfo.DoesNotExist or db.User.DoesNotExist:

		queue = db.updateQueue.objects.all()

		return render_to_response('noUserRank.html',
								{'userRank': user,
								'queue'  : queue},
								context_instance=RequestContext(request))

	game_db = get_object_or_404(db.gameInfo, psn_id=game)
	user_game_info_db = get_object_or_404(db.userGameInfo, game=game_db, user=user)
	user_game_db     = db.gameUserTrophyInfo.objects.filter(trophy__game=game_db, user=user).order_by('-date')
	user_trophy    = get_object_or_404(db.userTrophy, user=user)


	#
	trophy_have_list = user_game_db.values_list('trophy', flat=True)
	game_trophy_db   = db.gameTrophyInfo.objects.filter(game=game_db)
	user_not_game_db = game_trophy_db.exclude(id__in=trophy_have_list)

	game_list = []

	# Mostra o cabecalho com o jogo
	setGameDif(user_game_info_db)
	game_list.append(user_game_info_db)

	return render_to_response('userGameTrophy.html',
			{'user_trophy'     : user_trophy,
			 'user_game_trophy': user_game_db,
			 'user_not_game_trophy': user_not_game_db,
			 'user_game_info'  : game_list,
			 'psn_id'          : game_db.name,
			 'userRank'        : user},
			context_instance=RequestContext(request))

# Lista de jogos do usuario
def userGames(request, userName):

	try:
		user_auth = User.objects.get(username=userName)
		user = db.userInfo.objects.get(auth=user_auth)
	except db.userInfo.DoesNotExist or db.User.DoesNotExist:

		queue = db.updateQueue.objects.all()

		return render_to_response('noUserRank.html',
								{'userRank'  : user,
								'queue'  : queue},
								context_instance=RequestContext(request))

	user_trophy    = get_object_or_404(db.userTrophy, user=user)
	user_game_info = get_list_or_404(db.userGameInfo, user=user)

	game_list = []

	for game in user_game_info:
		setGameDif(game)
		game_list.append(game)

	game_list.sort(game_compare, reverse=True)

	return render_to_response('userGames.html',
				 {'user_trophy'   : user_trophy,
				 'userRank'   : user,
				 'user_game_info': game_list},
				 context_instance=RequestContext(request))


# Lista de jogos
def game(request, index):
	idx = index.upper()
	if not index:
		game_list = db.gameInfo.objects.filter(name__startswith="A").order_by('name')
	else:
		if idx == "ALL/":
			game_list = db.gameInfo.objects.all().order_by('name')
		elif idx == "0/":
			game_list = db.gameInfo.objects.filter(name__regex=r'^[0-9]').order_by('name')
			idx = "0-9/"
		elif idx == "JAP/":
			game_list = db.gameInfo.objects.filter(name__regex=r'^&').order_by('name')
		else:
			game_list = db.gameInfo.objects.filter(name__startswith=idx[0]).order_by('name')

	return render_to_response('Game.html',
				{'game_list' : game_list ,
				 'index'     : idx},
				 context_instance=RequestContext(request))

# Lista de trofeus de um jogo
def gameTrophy(request, game_id):
	game = get_object_or_404(db.gameInfo, psn_id=game_id)
	game_trophy_list = db.gameTrophyInfo.objects.filter(game=game).order_by('id')
	user_list_have = db.userGameInfo.objects.filter(game=game)
	user_list_plat = db.userGameInfo.objects.filter(game=game, platinum=1)
	user_list_100  = db.userGameInfo.objects.filter(game=game, perc_done=100)

	size = 0

	if len(user_list_have) is not 0:
		size += 1

	if len(user_list_plat) is not 0:
		size += 1

	if len(user_list_100) is not 0:
		size += 1

	return render_to_response('gameTrophy.html',
				{'trophy_list' : game_trophy_list,
				 'game'        : game,
				 'user_list_plat' : user_list_plat,
				 'user_list_have' : user_list_have,
				 'user_list_100'  : user_list_100,
				 'size'           : size},
				 context_instance=RequestContext(request))

# Ultimos trofeus do user
from django.core.paginator import Paginator, InvalidPage, EmptyPage

def lastUserTrophy(request, userName):
	user_auth = User.objects.get(username=userName)
	user = db.userInfo.objects.get(auth=user_auth)
	user_trophy    = get_object_or_404(db.userTrophy, user=user)

	user_trophy_list = db.gameUserTrophyInfo.objects.filter(user=user).order_by('-date')

	paginator = Paginator(user_trophy_list, 30) # Show 30 per page

	# Make sure page request is an int. If not, deliver first page.
	try:
		page = int(request.GET.get('page', '1'))
	except ValueError:
		page = 1

	try:
		trophy_list = paginator.page(page)
	except (EmptyPage, InvalidPage):
		trophy_list = paginator.page(paginator.num_pages)

	return render_to_response('userLastTrophy.html',
				{'user_trophy' : user_trophy,
				'user_trophy_list' : trophy_list},
				 context_instance=RequestContext(request))

def index(request):

	user_platinum_db = db.gameUserTrophyInfo.objects.filter(trophy__type = 'platinum').order_by('-date')[:10]
	user_trophy_db   = db.gameUserTrophyInfo.objects.filter().order_by('-date')[:10]

	return render_to_response('index.html',
							{'user_platinum_db' : user_platinum_db,
							'user_trophy_db'   : user_trophy_db},
							context_instance=RequestContext(request))

from django.db import connection

def boost_old(request, game_id):
	game  = get_object_or_404(db.gameInfo, psn_id=game_id)

	# Para o LBP vamos brincar com os seguintes trofeus:
	trophy_list = [ 'Look what I made!', 'Crowd Pleaser', 'Feel the love', 'Celebrity', 'Create' ]

	# Trofeu Publisher, o user deve ter pelo menos esse para estar na lista
	trophy_publish = 'Publisher'
	trophy_publish_db = db.gameTrophyInfo.objects.filter(game=game, name=trophy_publish)
	trophy_publish_db = trophy_publish_db[0]

	trophy_list_db = []

	# Lista de usuarios que tem LBP
	list_user = db.userGameInfo.objects.filter(game=game)

	# Lista temp
	list = []

	# Lista de usuarios que precisam dos trofeus
	list_user_trophy = []

	# Lista dos que ja completaram
	list_user_trophy_done = []

	# Listas dos que precisam mas nao tem nem o lvl "Publish", ou seja, nao tem nenhum lvl publicado
	list_user_trophy_nlvl = []

	for trophy in trophy_list:
		trophy_db = db.gameTrophyInfo.objects.filter(game=game, name=trophy)
		trophy_db = trophy_db[0]
		trophy_list_db.append(trophy_db)

	for user_db in list_user:
		list = []
		list.append(user_db)
		done = 1

			
		# Antes de adicionarmos na lista de users que devem ser beneficiados
		# vamos ver se o user tem o trofeu Publisher pelo meno
		trophy_user_publish_db = db.gameUserTrophyInfo.objects.filter(trophy=trophy_publish_db, user=user_db.user)
		if len(trophy_user_publish_db) is 1:
			publish = 1
		else:
			publish = 0

		for trophy_db in trophy_list_db:
			trophy_user_db = db.gameUserTrophyInfo.objects.filter(trophy=trophy_db, user=user_db.user)
			if len(trophy_user_db) is 0:
				list.append(None)
				done = 0
			else:

				list.append(trophy_user_db[0])

		if done:
			list_user_trophy_done.append(list)
		else:
			if publish:
				list_user_trophy.append(list)
			else:
				list_user_trophy_nlvl.append(list)

	render = render_to_response('Boost.html',
				{ 'trophy_list' : trophy_list_db,
				  'list_user_trophy'      : list_user_trophy,
				  'list_user_trophy_done' : list_user_trophy_done,
				  'list_user_trophy_nlvl' : list_user_trophy_nlvl,
				  'game'      : game},
				 context_instance=RequestContext(request))

	return render

from django.forms.models import modelformset_factory
from django.forms.models import inlineformset_factory
from django.db.models import Q
import sets

def boost(request, game_id, boost_name):

	game_db  = db.gameInfo.objects.get(psn_id=game_id)
	boost_db = db.boost.objects.get(name=boost_name)
	boost_trophy_db = db.boost_trophy.objects.filter(boost=boost_db).order_by('trophy__id')
	boost_trophy_earn_db = db.boost_trophy.objects.filter(boost=boost_db, type=1).order_by('trophy__id')
	boost_trophy_blck_db = db.boost_trophy.objects.filter(boost=boost_db, type=0).order_by('trophy__id')

	boost_user_db   = db.boost_user.objects.filter(boost=boost_db)
	trophy_db = db.gameTrophyInfo.objects.filter(game=game_db)

	UserFormSet   = inlineformset_factory(db.boost, db.boost_user,   extra=1, exclude='date')
	TrophyFormSet = inlineformset_factory(db.boost, db.boost_trophy, extra=1)

	# Vamos criar as listas dos usuarios:
	
	# Lista dos aptos a participar
	if len(boost_trophy_blck_db) is not 0:
		qs=boost_trophy_blck_db.values('trophy__id')
		user_db = db.gameUserTrophyInfo.objects.filter(trophy__in=qs, trophy__game=game_db).values_list('user', flat=True)
	else:
		user_db = db.gameUserTrophyInfo.objects.filter(trophy__game=game_db).values_list('user', flat=True)

	# Ordena e tira os duplicados
	new_user_db = list(sets.Set(user_db))

	# Lista dos que ja conseguiram todos os possiveis do boost, entao nao estarao na lista
	users_done_db = []
	users_need_db = []

	qs = boost_trophy_earn_db.values('trophy__id')

	for user_full in new_user_db:
		user_boost_db = db.userInfo.objects.get(id=user_full)
		full_db = db.gameUserTrophyInfo.objects.filter(user=user_boost_db, trophy__in=qs, trophy__game=game_db)
	
		full_new_db = []

		# Organiza
		for trophy_a in boost_trophy_earn_db:
			get = 0
			for trophy_b in full_db:	
				if trophy_a.trophy.id == trophy_b.trophy.id:
					full_new_db.append(trophy_b)
					get = 1
					break

			if get is 0:
				full_new_db.append(None)

		if len(qs) is len(full_db):
			users_done_db.append([ user_boost_db, full_new_db])
		else:
			users_need_db.append([ user_boost_db, full_new_db])

	if request.method == 'POST':

		try:
			user_formset   = UserFormSet(request.POST  , request.FILES, instance=boost_db)
		
			if user_formset.is_valid():
				user_formset.save()
		except:
			pass

		try:
			trophy_formset = TrophyFormSet(request.POST, request.FILES, instance=boost_db)

			if trophy_formset.is_valid():
				trophy_formset.save()
		except:
			pass

	user_formset   = UserFormSet  (instance=boost_db)
	trophy_formset = TrophyFormSet(instance=boost_db)

	return render_to_response('Boost.html',
				{ 'game'   : game_db, 'boost_db' : boost_db,
				  'user_formset'   : user_formset,
				  'trophy_formset' : trophy_formset,
				  'trophy_db'      : trophy_db,
				  'boost_trophy_db': boost_trophy_db,
				  'boost_trophy_earn_db': boost_trophy_earn_db,
				  'boost_trophy_blck_db': boost_trophy_blck_db,
				  'boost_user_db'  : boost_user_db,
				  'users_need_db'  : users_need_db,
				  'users_done_db'  : users_done_db},
				 context_instance=RequestContext(request))

def boost_index(request):
	boost_db = db.boost.objects.all()

	return render_to_response('BoostIndex.html',
				{'boost_db' : boost_db},
				context_instance=RequestContext(request))

def boost_game(request, game_id):

	game_db  = db.gameInfo.objects.get(psn_id=game_id)
	boost_db = db.boost.objects.filter(game=game_db)

	BoostFormSet = inlineformset_factory(db.gameInfo, db.boost, extra=1,exclude='date')

	if request.method == 'POST':
		boost_formset  = BoostFormSet(request.POST, request.FILES, instance=game_db)

		if boost_formset.is_valid():
			boost_formset.save()

	boost_formset = BoostFormSet(instance=game_db)

	return render_to_response('BoostGame.html',
				{ 'game'   : game_db, 'boost_db' : boost_db,
				  'boost_formset' : boost_formset},
				 context_instance=RequestContext(request))

def gameTrophyDetail(request, game_id, trophy_id):

	game_db   = db.gameInfo.objects.get(psn_id=game_id)
	trophy_db = db.gameTrophyInfo.objects.get(game=game_db, total_id=trophy_id)
	user_have_db = db.gameUserTrophyInfo.objects.filter(trophy=trophy_db)
	
	#
	user_have_list      = user_have_db.values_list('user', flat=True)
	user_have_game_list = db.gameUserTrophyInfo.objects.filter(trophy__game=game_db).values_list('user', flat=True)
	user__have_db       = db.userInfo.objects.filter(id__in=user_have_game_list)
	user_not_have_db    = user__have_db.exclude(id__in=user_have_list)

	#trophy_have_list = user_game_db.values_list('trophy', flat=True)
	#game_trophy_db   = db.gameTrophyInfo.objects.filter(game=game_db)
	#user_not_game_db = game_trophy_db.objects.exclude(id__in=trophy_have_list)

	# Buscas no google e no youtube
	return render_to_response('gameTrophyDetail.html',
				  {'user_have_db' : user_have_db,
				  'user_not_have_db' : user_not_have_db,
				  'game' : game_db,
				  'trophy' : trophy_db},
				 context_instance=RequestContext(request))

from django.contrib.comments.models import Comment
from django.http import HttpResponseRedirect

def comment_posted( request ):
	if request.GET['c']:
		post_id  = int(request.GET['c'])
		post = Comment.objects.get( pk=post_id )

		if post:
			return HttpResponseRedirect( post.get_absolute_url() )

		return HttpResponseRedirect( "/" )


def rankGame(request):
	# Pegamos todos os jogos que tem pelo menos 1 trofeu
	game_list = db.userGameInfo.objects.exclude(total = 0).values_list('game', flat=True).order_by('game')
	game_list = list(sets.Set(game_list))

	game_rank = []

	for game in game_list:
		game_db      = db.gameInfo.objects.get(id=game)
		game_info_db = db.userGameInfo.objects.filter(game=game_db)

		# Quantas pessoas tem a platina
		game_plat = len(game_info_db.filter(platinum = 1))

		# Se ninguem tem, pula o jogo
		if game_plat is 0:
			continue

		# Quantas pessoas tem o jogo
		game_have = len(game_info_db)
	
		# Quantas pessoas tem o jogo e tem mais de um trofeu
		game_have_m = len(game_info_db.exclude(total = 0))

		# Quantas pessoas tem a platina
		game_plat = len(game_info_db.filter(platinum = 1))

		# Quantos trofeus este jogo tem
		game_trophy = len(db.gameTrophyInfo.objects.filter(game=game_db))

		# Quantos trofeus todo mundo tem deste jogo
		game_user_trophy = len(db.gameUserTrophyInfo.objects.filter(trophy__game=game_db))

		# Percentual: Pessoas que tem 1 trofeu - Pessoas que tem platina
		game_plat_perc = (game_plat*100) / game_have_m

		# Junta tudo na lista
		game_rank.append([game_db, game_have, game_have_m, game_plat, game_trophy, game_user_trophy, game_plat_perc])

	game_rank.sort(game_rank_compare)
	
	return render_to_response('RankGame.html',
				  {'game_rank' : game_rank},
				 context_instance=RequestContext(request))

import os
from django.contrib.auth.decorators import login_required

@login_required()
def profile(request):
	user_db = User.objects.get(id=request.user.id)

	changeInfo = inlineformset_factory(db.User, db.userInfo, can_delete=False, exclude=["country", "ps3card_url", "card_bg_url"])

	if request.method == 'POST':
		changeInfo_formset = changeInfo(request.POST, request.FILES, instance=user_db)

		if changeInfo_formset.is_valid():
			changeInfo_formset.save()
			old_dir = os.getcwd()
			os.chdir("/home/fabriciols/ps3t/myps3t/")
			subprocess.call(['python', 'psn_card.py', '%s' %user_db.username])
			os.chdir(old_dir)

	changeInfo_formset = changeInfo(instance=user_db)

	return render_to_response('Profile.html', { 'form': changeInfo_formset},
				 context_instance=RequestContext(request))

from django.contrib.auth.models import User
from datetime import datetime, timedelta
from ps3t.lastActivityDate.models import UserActivity

def get_online_users(num):
	fifteen_minutes = datetime.now() - timedelta(minutes=15)
	sql_datetime = datetime.strftime(fifteen_minutes, '%Y-%m-%d %H:%M:%S')
	#users = UserActivity.objects.filter(last_activity_date__gte=sql_datetime, user__auth__is_active__exact=1).order_by('-last_activity_date')[:num]
	users = UserActivity.objects.filter( user__auth__is_active__exact=1).order_by('-last_activity_date')[:num]
	return [u.user for u in users]
